package com.ky.manage.activity.msg;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ky.manage.R;
import com.ky.manage.adapter.MsgDetailAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.model.MsgCenterItemModel;
import com.ky.manage.model.response.MsgListResp;
import com.ky.manage.ui.RecycleViewDivider;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 消息列表页
 */
public class MsgListActivity extends BaseActivity {

    private String title, type;
    private MsgDetailAdapter mMsgDetailAdapter;
    private RefreshLayout refreshLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_msg_list;
    }

    @Override
    protected void initView() {
        findTextView(R.id.page_title_tv, TextUtils.isEmpty(title) ? "消息列表" : title);
        findView(R.id.back_iv, v -> {
            finish();
        });
        RecyclerView msgRecyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        msgRecyclerView.setLayoutManager(linearLayoutManager);
        msgRecyclerView.addItemDecoration(new RecycleViewDivider(mCurActivity, LinearLayoutManager.VERTICAL,
                ScreenUtils.dp2px(3), mCurActivity.getColor(R.color.gray_light)));
        mMsgDetailAdapter = new MsgDetailAdapter(R.layout.layout_msg_detail_item, new ArrayList<>());
        mMsgDetailAdapter.setEmptyView(R.layout.layout_empty_data);
        msgRecyclerView.setAdapter(mMsgDetailAdapter);
        mMsgDetailAdapter.notifyDataSetChanged();

        refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            reqMsgListInfoData();
        });
        refreshLayout.setEnableLoadMore(false);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (null != intent) {
            title = intent.getStringExtra("title");
            type = intent.getStringExtra("type");
        }
        Log.d("zhaoyan", "title = " + title + ", type = " + type);
    }


    private boolean mIsReqListData = false;

    private void reqMsgListInfoData() {
        if (mIsReqListData) {
            return;
        }
        mIsReqListData = true;
        RequestParams requestParams = new RequestParams();
        requestParams.put("isRead", 1);//阅读状态(0已读， 1未读)
        requestParams.put("status", 0);//公告状态（0正常 1关闭）
        requestParams.put("noticeType", type);//公告类型（1通知 2公告）
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/getNoticeList", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("reqMsgListInfoData", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString
                        + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("获取消息列表数据失败：" + throwable.getMessage());
                refreshLayout.finishRefreshWithNoMoreData();
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("reqMsgListInfoData", "onSuccess statusCode = " +
                        statusCode + ", responseString = "+ responseString);
                MsgListResp msgListResp = BusinessHttpReqUtils.getInstance().parseJsonObj
                        (responseString, MsgListResp.class);
                if (null != msgListResp) {
                    if (msgListResp.code == 200) {
                        parseMsgList2MstModel(msgListResp.rows);
                    } else if (msgListResp.code == 401){
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mCurActivity);
                    } else {
                        ToastUtils.showRoundRectToast("获取消息列表数据失败: " + msgListResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取消息列表数据失败");
                }
                refreshLayout.finishRefresh();
                mIsReqListData = false;
            }
        });
    }

    private void parseMsgList2MstModel(List<MsgListResp.MsgItemInfo> rows) {
        List<MsgCenterItemModel> msgCenterItemModelList = new ArrayList<>();
        if (null != rows && !rows.isEmpty()) {
            for (MsgListResp.MsgItemInfo msgItemInfo : rows) {
                MsgCenterItemModel systemNoticeItemModel = new MsgCenterItemModel();
                systemNoticeItemModel.content = msgItemInfo.noticeContent;
                systemNoticeItemModel.date = msgItemInfo.updateTime;
                systemNoticeItemModel.type = msgItemInfo.noticeType;
                systemNoticeItemModel.content = msgItemInfo.noticeContent;
                systemNoticeItemModel.title = msgItemInfo.noticeTitle;
                msgCenterItemModelList.add(systemNoticeItemModel);
            }
            mMsgDetailAdapter.setList(msgCenterItemModelList);
        }
    }
}
